<?php
class Mkeyword extends CI_Model {

	function Mkeyword(){
		parent::__construct();
                
	}
        
        public function generate($tanggal) {
             //$query = $this->db->where(array('user_id' =>$user_id,'track_date'=>$tanggal))->get('t_trx_track');
            $sqlUser = "select * from t_mtr_user where user_group_id = 8 or user_group_id = 9";
            $queryUser = $this->db->query($sqlUser);
            
            $numberUser = $queryUser->num_rows();
            $key = array();
            //select random keyword
            $sqlKey = "select keyword from t_mtr_keyword_bank order by random() limit $numberUser";
            $queryKey = $this->db->query($sqlKey);
            $n = 0;
            foreach($queryKey->result() as $rowKey) {
                $key[$n] = $rowKey->keyword;
                $n++;
            }
                 
            for($i=$n;$i<=$numberUser;$i++) {
                $key[$i] = "JUST KEY";
            }
            
            $sql = "insert into t_keywords (user_id,valid_date,keyword,client) values ";
            $b = 0;
            foreach($queryUser->result() as $row) {
                if($b <> 0) {
                    $sql .= ", ";
                }
                $sql .= " ('$row->user_id','$tanggal','$key[$b]','mobile-android')";
                $b++;
            }
            
            $queryInsert = $this->db->query($sql);
            
            return $this->db->affected_rows();
        }
        
        public function deleteKeyword($tanggal) {
            $sql = "delete from t_keywords where valid_date = '$tanggal'";
            $queryInsert = $this->db->query($sql);
            
            return $this->db->affected_rows();
        }
        
        public function getKeyword($tanggal = "") {
            		
            $sql = "select key_id, user_id, valid_date, keyword, client from t_keywords ";
            if($tanggal <> "") {
                $sql .= "where valid_date = '$tanggal' ";
            }
            $sql .= "order by valid_date desc"; 		                
            $query = $this->db->query($sql);
            if( $query->num_rows() > 0 ) {
                    return $query->result();
            } else {
                    return array();
            }
        }
        
}
?>
